﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using MISAPP.Classify.Service;
using System.Configuration;

/// <summary>
/// Utility 的摘要描述
/// </summary>
public class Utility
{

    #region static method 

    /// <summary>
    /// 針對usercontrol 找
    /// </summary>
    /// <param name="p_mi"></param>
    /// <param name="p_methodName"></param>
    /// <param name="p_paraTypes">要找出來的參數型別</param>
    /// <param name="p_userControl"></param>
    /// <returns></returns>
    public static System.Reflection.MethodInfo FindMethodInfo(System.Reflection.MethodInfo[] p_mi
        ,string p_methodName
        ,Type[] p_paraTypes
        )
    {
        /*
        bool ok = true;
        System.Reflection.MethodInfo rtnMethod = null;
        foreach(System.Reflection.MethodInfo m in p_mi)
        {
            if (m.Name.ToLower().Equals(p_methodName.ToLower()))
            {
                ok = true;
                System.Reflection.ParameterInfo[] paraInfo = m.GetParameters();
                if (p_paraTypes == null)
                {
                    rtnMethod = m;
                    break; 
                }
                //if (paraInfo.Length != p_paraTypes.Length){ break; }
                if (paraInfo.Length == p_paraTypes.Length)
                {
                    for (int i = 0; i < paraInfo.Length; i++)
                    {
                        //確認型別都是我要的
                        if (paraInfo[i].ParameterType != p_paraTypes[i])
                        {
                            ok = false;
                            break;
                        }
                    }
                    rtnMethod = (ok == true) ? m : null;
                    if (rtnMethod != null) { break; }
                }
                
            }
        }
        return rtnMethod;
         */
        return MISAPP.Classify.Service.Utility.FindMethodInfo(
            p_mi, p_methodName, p_paraTypes);
    }

    public static int GetGridViewRowIndexForTableRecord(int p_pageIndex, int p_rowIndex, int p_pageSize)
    {
        int rtnValue = 0;
        if (p_pageIndex == 0)
        {
            rtnValue = p_rowIndex;
        }
        else
        {
            rtnValue = p_pageSize * p_pageIndex + p_rowIndex;
        }
        return rtnValue;
    }

    public static object GetServiceObject(string p_serviceName)
    {
        object o = null;
        if (!string.Empty.Equals(p_serviceName))
        {
            Type t = null;
            string serviceDll, bin, path, dll;
            serviceDll = Utility.GetWebConfigAppSettingsValue("serviceDll");
            bin = Utility.GetWebConfigAppSettingsValue("binParh");
            path = string.Format(@"{0}{1}", HttpContext.Current.Server.MapPath("~"), bin);
            dll = string.Format(@"{0}{1}", path, serviceDll);
            System.Reflection.Assembly instance = System.Reflection.Assembly.LoadFrom(dll);
            t = instance.GetType(p_serviceName);
            o = System.Activator.CreateInstance(t);
        }
        return o;
    }

    public static object GetAttributeDefaultValue(string p_attributesName,Control p_this)
    {
        System.ComponentModel.AttributeCollection attributes =
                   System.ComponentModel.TypeDescriptor.GetProperties(p_this)[p_attributesName].Attributes;
        System.ComponentModel.DefaultValueAttribute myAttribute =
            (System.ComponentModel.DefaultValueAttribute)attributes[typeof(System.ComponentModel.DefaultValueAttribute)];
        return myAttribute.Value;
    }

    //public static void LoadJquery(Control p_control,Type p_type)
    //{
    //    System.Web.UI.ScriptManager.RegisterClientScriptInclude(
    //          p_control
    //        , p_control.GetType(), "jquery"
    //        , Utility.GetWebConfigAppSettingsValue("jquery"));

    //    System.Web.UI.ScriptManager.RegisterClientScriptInclude(
    //         p_control
    //         , p_control.GetType(), "jqueryUI"
    //       , Utility.GetWebConfigAppSettingsValue("jqueryUI"));

    //}

    /// <summary>
    /// 
    /// </summary>
    /// <param name="p_control">控制項</param>
    /// <param name="p_name">要引用的jquery name</param>
    /// <param name="p_blockName">要註冊在script 上的名字</param>
    public static void LoadJquery(Control p_control, string p_name, string p_blockName)
    {
        System.Web.UI.ScriptManager.RegisterClientScriptInclude(
             p_control
             , p_control.GetType(), p_name
           , Utility.GetWebConfigAppSettingsValue(p_blockName));
        //System.Web.UI.ScriptManager.RegisterClientScriptBlock(
        //    p_control
        //    , p_control.GetType(), p_name
        //  , Utility.GetWebConfigAppSettingsValue(p_blockName),true);
    }

    /// <summary>
    /// 在這統一回傳Web.config 中 appSettings 中的值
    /// </summary>
    /// <param name="p_key"></param>
    /// <returns></returns>
    public static string GetWebConfigAppSettingsValue(string p_key)
    {
        return ConfigurationManager.AppSettings[p_key].ToString();
    }

    public static bool GetExclusiveAccont(string p_exclusive)
    {
        return MISAPP.Classify.Service.Utility.GetExclusiveOfAccount(p_exclusive);
    }
    /// <summary>
    /// 傳入YYYYMM回傳XXX年XX月
    /// </summary>
    /// <param name="p_ym"></param>
    /// <returns></returns>
    public static string GetTaiwanYM(string p_ym)
    {
        string yyyy,tYYYY, mm;
        yyyy = p_ym.Substring(0, 4);
        mm = p_ym.Substring(4, 2);
        tYYYY = Convert.ToString(Convert.ToInt16(yyyy) - 1911);
        return string.Format("{0}年{1}月",tYYYY,mm);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>return 10001</returns>
    public static string GetTaiwanYM()
    {
        string yyyy, mm;
        //預設是執行目前的月份-1
        DateTime dd = DateTime.Now.AddMonths(-1) ;
        yyyy = Convert.ToString(dd.Year - 1911) ;
        mm = string.Format("0{0}", dd.Month.ToString());
        mm = mm.Length.Equals(3) ? mm.Substring(1) : mm;
        return string.Format("{0}{1}",yyyy,mm);
    }

    public static string GetYYYYMM(string p_twYM)
    {
        int yyyy;
        string mm;
        yyyy = Convert.ToInt16(p_twYM.Substring(0,3))+ 1911;
        mm = p_twYM.Substring(3);
        return string.Format("{0}{1}",yyyy.ToString(),mm) ;
    }

    public static string GetNewGridViewCaption(string p_lString, string p_rString)
    {
        string newCaption = string.Empty;
        newCaption = string.Format(@"
        <table border=0 width='100%'>
            <tr>
                <td class='forCaption' align='left'>{0}</td>
                <td class='forCaption' width='50%'></td>
                <td class='forCaption' align='right'>{1}</td>
            </tr>
        </table>
        ", p_lString, p_rString);
        return newCaption;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="upLoad"></param>
    /// <param name="grpName">getResultValue(2)</param>
    /// <param name="serverMpath">Server.MapPath("~")</param>
    /// <returns></returns>
    public static string SaveAS(System.Web.UI.WebControls.FileUpload upLoad
        ,string grpName,string serverMpath
        )
    {
        string fileName, strDate,uploadFile ;
        uploadFile = string.Empty;
        strDate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
            .Replace(":", "").Replace("/", "").Replace(" ", "");
        
        fileName = string.Format("{0}_{1}_{2}",
             grpName
            , strDate
            , System.IO.Path.GetFileName(upLoad.FileName)            
            );

        uploadFile = string.Format("{0}\\upload\\{1}", serverMpath, fileName);
        upLoad.SaveAs(uploadFile);

        return uploadFile;
    }

    public static string TemplateToDownload(string p_path,string p_name
        ,string p_ext)
    {
        string sourceFile, targetFile, strDate;
        strDate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
            .Replace(":", "").Replace("/", "").Replace(" ", "");
        System.Threading.Thread.Sleep(1000);
        sourceFile = string.Format("{0}\\Template\\{1}",
            p_path, p_name);
        targetFile = string.Format("{0}\\Download\\Template{1}.{2}",
            p_path, strDate,p_ext);
        System.IO.File.Copy(sourceFile, targetFile);
        return targetFile;
    }

    /// <summary>
    /// 清除掉Session
    /// </summary>
    public static void SessionClear()
    {
        List<string> result = HttpContext.Current.Session["result"] as List<string>;
        HttpContext.Current.Session.Clear();
        HttpContext.Current.Session["result"] = result;
    }

    /// <summary>
    /// 檢查是否為日期
    /// </summary>
    /// <param name="p_ym">201104</param>
    /// <returns></returns>
    public static bool IsDateYM(string p_ym)
    {
        bool ok = false;
        if (p_ym.IndexOf('_') < 1)
        { 
            ok = MISAPP.Classify.Service.Utility.IsDate(p_ym);
        }
        else
        {
            //有日期區間
            string[] yms = p_ym.Split('_');
            ok = MISAPP.Classify.Service.Utility.IsDate(yms[0])
                == MISAPP.Classify.Service.Utility.IsDate(yms[1])
                ?true:false;            
        }
        return ok;
    }

    public static string GetDeEncrypt(string p_val)
    {
        return MISAPP.Classify.Service.Utility
            .GetEncryptOrDeEncrypt(p_val);
    }
    #endregion    
}
